<template>
  <div class="box">
    <div class="go-back">
      <el-button  :icon="ArrowLeftBold" plain type="info" @click="router.go(-1)">返回</el-button>
    </div>
    <div class="startExam">
      <div class="aside">
        <div class="viewBox">
          <div class="question" v-if="questionLoad">
            <div class="viewTitle">{{ sortIndex }}、{{ source==1 ? questionDetails.questionTitle:questionDetails.errorQuestion }}</div>
            <div class="questionBox" >
              <!-- 单选 -->
              <template v-if="questionDetails.questionType==0">
                <el-radio-group v-model="questionDetails.answer" >
                  <div v-if="questionLoad"
                      v-for="(option,ins) in questionDetails.options"
                      :key="ins"
                      class="form-item-with-radio"
                  >
                    <el-radio  :label="option.id" :value="`${option.id}`" :disabled="questionDetails.isStatus==1||questionDetails.isStatus==2" >{{source==1 ? option.optionTitle:option.options}}. &nbsp;{{source==1 ? option.optionDescribe:option.optionDescribe}}</el-radio>
                  </div>
                </el-radio-group>
              </template>

              <!-- 多选 -->
              <template v-if="questionDetails.questionType==1">
                <el-checkbox-group v-model="questionDetails.answer" >
                  <div v-if="questionLoad"
                      v-for="(option,ins) in questionDetails.options"
                      :key="ins"
                      class="form-item-with-radio"
                  >
                    <el-checkbox :label="option.id" :value="`${option.id}`" :disabled="questionDetails.isStatus==1||questionDetails.isStatus==2">{{source==1 ? option.optionTitle:option.options}}. &nbsp;{{source==1 ? option.optionDescribe:option.optionDescribe}}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </template>

              <!-- 判断 -->
              <template v-if="questionDetails.questionType==2">
                <el-radio-group v-model="questionDetails.answer" size="small" :disabled="questionDetails.isStatus==1||questionDetails.isStatus==2">
                  <el-radio-button v-for="(option,ins) in questionDetails.options" :key="ins" :label="option.id" :value="`${option.id}`" border>{{source==1 ? option.optionDescribe:option.optionDescribe}}</el-radio-button>
                </el-radio-group>
              </template>

              <!-- 主观题 -->
              <template v-if="questionDetails.questionType==3">
                <el-input type="textarea"  :autosize="{ minRows: 7}" placeholder="" v-model="questionDetails.answer" :disabled="questionDetails.isStatus==1||questionDetails.isStatus==2"></el-input>
              </template>
            </div>
            <div class="examBtn" style="margin: 30px 0;">
              <el-button type="primary"  @click="submitQuestions()" :disabled="questionDetails.isStatus==1||questionDetails.isStatus==2">查看答案并提交</el-button>
            </div>

            <div v-if="answerOpen">
              <div class="answer" >
                <h3>答案</h3>
                <p>{{questionAnswer}}</p>
                <p style="text-align: center" v-if="source==1" @click="commentClick()">
                  <el-icon v-if="commentControl.commentClass==1"><CaretBottom /></el-icon>
                  <el-icon v-else><CaretTop /></el-icon>{{ commentControl.title }}
                </p>
                  <QuestionCommentView v-if="commentOpen" :currentQuestionId="currentQuestionId"/>
              </div>
          </div>
        </div>
      </div>
      </div>
      <div class="main">
        <div class="question-numbers">
<!--          <div class="countdown-timer">-->
<!--            <h3>考试结束倒计时</h3>-->
<!--            <div class="time">{{ data.countdown }}</div>-->
<!--          </div>-->
          <h3>题号</h3>
          <div class="numbers">
            <div
                v-for="(question, index) in questionsList"
                :key="index"
                :class="['number-button']"
                :style="{ backgroundColor: sortIndex === index + 1 ? '#409EFF' : questionsList[index].isStatus===1 ? '#67C23A' : questionsList[index].isStatus===2 ? '#F56C6C' : '' }"
                @click="changeQuestion(index,question.id)"
            >
              {{ index + 1 }}
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,reactive, onMounted,onBeforeUnmount,computed } from 'vue'
import { useRoute } from 'vue-router';
import router from '@/router'
import axios from '@/axios/index.js'
import {ElMessage,ElMessageBox,ElLoading} from 'element-plus'
import {ArrowLeftBold, CaretBottom, CaretTop} from "@element-plus/icons-vue";
import QuestionCommentView from "@/views/question/questionBank/QuestionCommentView.vue";

const route = useRoute();
let questionsList = ref()
let source = ref(0);
let subjectId = ref(0);
let answerOpen = ref(false);
let commentOpen = ref(false);
let commentControl = reactive({
  commentClass:1,
  title:'查看评论'
});

let data = reactive({
  examEndTime:"00:00:00",
  countdown:"",
  examEnd:false,
});

let questionDetails = reactive({});
let statusList = ref([]);

let currentQuestionId = ref()
let studentAnswer = reactive({
  questionId:0,
  answer:''
})

let answerList =ref([]);
let answerUnCommitList =ref([]);
let questionAnswer = ref('');

let sortIndex = ref(1);
let questionLoad = ref(false);

function commentClick(){
if (commentControl.commentClass==1){
    commentControl.commentClass=0;
    commentControl.title='收起评论'
    commentOpen.value=true;
  }else{
    commentControl.commentClass=1;
    commentControl.title='查看评论'
    commentOpen.value=false;
  }
}

//判断题目
function submitQuestions(){
  if (questionDetails.answer==null||questionDetails.answer==undefined||questionDetails.answer==""){
    ElMessage({
      type: 'error',
      message: "请填写答案！",
    })
    return;
  }
  if(source.value==1){
    studentAnswer.questionId = questionDetails.id;
    axios.post("/fquestion/judgeQuestion",{
      questionId:questionDetails.id,
      answer:questionDetails.answer
    }).then(res=>{
      if(res.data.code==200){
        if (res.data.message=="回答正确"){
          ElMessage({
            type: 'success',
            message: res.data.message,
          })
          questionsList.value[sortIndex.value-1].isStatus=1;
        }else if (res.data.message=="回答错误"){
          ElMessage({
            type: 'error',
            message: res.data.message,
        })
          questionsList.value[sortIndex.value-1].isStatus=2;
      }else {
          ElMessage({
            type: 'success',
            message: res.data.message,
          })
          questionsList.value[sortIndex.value-1].isStatus=1;
        }
      }
      const addAnswer = {
        questionId:studentAnswer.questionId,
        questionAnswer:studentAnswer.answer,
        questionAnalysis:res.data.data.analysis,
        studentAnswer:studentAnswer.answer
      }
      for (let i = 0; i < res.data.data.options.length; i++) {
        if(res.data.data.options[i].status==1){
          if (questionDetails.questionType==1){
            addAnswer.questionAnswer+=res.data.data.options[i].optionTitle;
          }else {
            addAnswer.questionAnswer=res.data.data.options[i].optionTitle;
            break;
          }
        }
      }
      answerList.value.push(addAnswer);
      if (res.data.data.analysis == null){
        questionAnswer.value = "正确答案："+addAnswer.questionAnswer+" ，暂无解析"
      }else{
        questionAnswer.value = "正确答案："+addAnswer.questionAnswer+"   "+res.data.data.analysis;
      }
      answerOpen.value = true;
    })
  }else {
    studentAnswer.questionId = questionDetails.id;
    console.log(questionDetails.answer)
    axios.post("/ferrorNotebooks/judgeErrQuestion",{
      questionId:questionDetails.id,
      answer:questionDetails.answer
    }).then(res=>{
      console.log(res.data.data)
      console.log(res.data.message)
      if(res.data.code==200){
        if (res.data.message=="回答正确"){
          ElMessage({
            type: 'success',
            message: res.data.message,
          })
          questionsList.value[sortIndex.value-1].isStatus=1;
        }else if (res.data.message=="回答错误"){
          ElMessage({
            type: 'error',
            message: res.data.message,
          })
          questionsList.value[sortIndex.value-1].isStatus=2;
        }else {
          ElMessage({
            type: 'success',
            message: res.data.message,
          })
          questionsList.value[sortIndex.value-1].isStatus=1;
        }
      }
      const addAnswer = {
        questionId:studentAnswer.questionId,
        questionAnswer:studentAnswer.answer,
        questionAnalysis:res.data.data.analysis,
        studentAnswer:studentAnswer.answer
      }
      for (let i = 0; i < res.data.data.options.length; i++) {
        if(res.data.data.options[i].status==1){
          addAnswer.questionAnswer+=res.data.data.options[i].options;
        }
      }
      answerList.value.push(addAnswer);
      if (res.data.data.analysis == undefined){
        questionAnswer.value = "正确答案："+addAnswer.questionAnswer+" ，暂无解析"
      }else{
        questionAnswer.value = "正确答案："+addAnswer.questionAnswer+"   "+res.data.data.analysis;
      }
      answerOpen.value = true;
    })
  }
}

/**切换题目*/
function changeQuestion(index,questionId){
  //当前题目的id
  currentQuestionId.value = questionId
    
  commentControl.commentClass=1;
    commentControl.title='查看评论'
    commentOpen.value=false;

  questionLoad.value=false;
  answerOpen.value=false;
  sortIndex.value=index+1;
  questionDetails = questionsList.value[index];
  if (questionsList.value[index].isStatus==1||questionsList.value[index].isStatus==2){
    for (let i = 0; i < answerList.value.length; i++) {
      if (answerList.value[i].questionId==questionDetails.id){
        studentAnswer.answer=answerList.value[i].studentAnswer;
        studentAnswer.questionId=answerList.value[i].questionId;
        if (answerList.value[i].questionAnalysis === undefined||answerList.value[i].questionAnalysis === null){
          questionAnswer.value = "正确答案："+answerList.value[i].questionAnswer+" ，暂无解析"
        }else{
          questionAnswer.value = "正确答案："+answerList.value[i].questionAnswer+"  "+answerList.value[i].questionAnalysis
        }
        break;
      }
    }
    answerOpen.value=true;
  }
  questionDetails.options=questionsList.value[index].options;
  questionLoad.value=true
}


const getQuestionsList = async() =>{
  questionLoad.value=false;
  let array = route.query.ids;
  source.value = route.query.source;
  if (source.value === null || source.value === undefined || source.value === '') {
    ElMessage({
      type: 'error',
      message: '请选择题目',
    })
    return ;
  }
  subjectId.value=route.query.subjectId;
  if (source == 1){
    if (subjectId.value === null || subjectId.value === undefined || subjectId.value === 0) {
      if (array.length === 0 || array === undefined){
        ElMessage({
          type: 'error',
          message: '请选择学科',
        })
        return ;
      }
    }
  }

  try {
    let path = "";
    //1： 来自题库的题目 ， 0： 来自错题本题目
    if (source.value==1){
      path = "/fquestion/getQuestions";
      const res = await axios.get(""+path,{
        params:{
          ids: array==undefined? []: array.join(','),
          subjectId:subjectId.value
        }
      })
      if(res.data.code===200){
        // loadingInstance.value.close()
        questionsList.value = res.data.data;
        for (let i = 0; i < questionsList.value.length; i++) {
          if (questionsList.value[i].questionType==1)
            questionsList.value[i].answer = [];
          else{
            questionsList.value[i].answer = '';
          }
          questionsList.value[i].isStatus = 0;
        }
        console.log(questionsList.value)
        questionDetails=questionsList.value[0];
        questionLoad.value=true;
        //默认是第一个题目的id
        currentQuestionId.value = questionsList.value[0].id
      }
    }else {
      path = "/ferrorNotebooks/getErrQuestions"
      const res = await axios.get(""+path)
      if(res.data.code===200){
        questionsList.value = res.data.data
        console.log(questionsList);
        questionDetails=questionsList.value[0];
        if (questionDetails.questionType==1){
          studentAnswer.answer=[]
        }else {
          studentAnswer.answer=''
        } 
        questionLoad.value=true;
      }
    }
    for (let i = 0; i < questionsList.value.length; i++) {
      statusList.value.push(0);
    }
    console.log(questionsList.value);
    currentQuestionId.value = questionsList.value[0].id
  } catch (error) {
    console.log(error);
  }

}
onMounted(()=>{
  getQuestionsList()
})
// 页面刷新提示
onBeforeUnmount(() =>{
  window.removeEventListener('beforeunload', handleBeforeUnload);
})
const handleBeforeUnload = (event) => {
  const message = '您确定要离开此页面吗？';
  event.returnValue = message;
  return message;
}

</script>

<style scoped lang="less">
*{
  font-size: 16px;
}
.box{
  width: 100%;
  padding: 50px;
  .startExam{
    height: 100%;
    display: flex;
    justify-content: space-between;
  }
  .aside{
    width: 68%;
    border: 2px solid #e3e3e3;
    height: 100%;
  }
  .main{
    width: 30%;
    border: 2px solid #e3e3e3;
    height: 100%;
  }
}
.aside{
  overflow-y: scroll;
  height: 100%;
  width: 70%;
  border: 1px solid #ccc;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .viewBox{
    padding: 10px 40px;
    height: calc(100vh - 200px);
    .h3{
      display: flex;
      align-items: center;
    }
    .viewTitle{
      margin: 20px;
      ::v-deep el-radio{
        margin-right: 10px;
      }
    }
    .viewBox-item{
      margin:10px 0;
      display: flex;
      >div{
        // margin-left: 20px;
        width: 100%;
        font-size: 14px;
      }
    }
  }

}
.main{
  height: 100%;
  width: 27%;
  border: 1px solid #ccc;
  padding: 10px 40px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .numbers {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .number-button {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    background-color: #eee;
    color: #000;
  }

  .number-button.active {
    background-color: #007bff;
    color: #fff;
  }

  .number-button.answered {
    background-color: #28a745;
    color: #fff;
  }
  .countdown-timer {
    text-align: center;
    margin-bottom: 20px;
  }

  .time {
    font-size: 2em;
    font-weight: bold;
  }
}
.examBtn{
  display: flex;
  justify-content: end;
  margin: 40px;
}
::v-deep .el-button.is-circle {
  width: 20px;
  height: 20px;
}
.form-item-with-radio{
  display: flex;
  width: 100%;
  box-sizing: border-box;
  align-items: center;
  .el-checkbox{
    margin-right: 32px;
  }
}
.question{
  .questionBox{
    font-size: 20px;
    margin-left: 50px;
  }
}

.numbers {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.number-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-color: #eee;
  color: #000;
}

.number-button.active {
  background-color: #007bff;
  color: #fff;
}
.go-back{
  font-size: 14px;
  position: absolute;
  margin-top: -40px;
}

</style>